module Controllers.Login(handleLogin, handleCompleteLogin) where

import Session(Session(..), UserID(..), writeSession)
import Happstack.Server(ok, toResponse, ServerPart, Response)
import Web.Authenticate.OpenId
import Text.Digestive.Blaze.Html5 (label, inputText)
import Controllers.Digestive(runForm)
import Happstack.Server(seeOther)
import Text.Digestive.Types((++>))
import Control.Monad.IO.Class(liftIO)
import Happstack.Server.RqData(lookPairs)


-- Login form handler. Currently just logs in as 'mosk'.
handleLogin :: ServerPart Response
handleLogin = do
    runForm handleSubmit loginForm

loginForm = label "OpenId" ++> inputText Nothing

handleSubmit :: String -> ServerPart Response
handleSubmit userProvidedId = do
    forwardUrl <- liftIO $ getForwardUrl  -- TODO: handle errors
        userProvidedId
        "http://tuura.net/tuura/completeLogin" -- TODO: relative URL
        Nothing
        []
    seeOther forwardUrl (toResponse ())

handleCompleteLogin :: ServerPart Response
handleCompleteLogin = do
    rqPairs <- lookPairs
    let valPairs = [(key,val) | (key, Right val) <- rqPairs]
    (Identifier userId, additionalData) <- liftIO $ authenticate valPairs
    writeSession (Session (UserID userId)) >> ok (toResponse $ "logged in " ++ userId ++ "/n" ++
        "Additional info:\n" ++ concat(map ((++"\n").show) additionalData))
